package dragon.oauth;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

/**
 * 自定义clientDetailsService，从哪里获取client信息
 */
@Component("myClientDetailsService")
public class MyClientDetailsService implements ClientDetailsService {

    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        //通过业务逻辑去实现查找client相关信息
        BaseClientDetails clientDetails = new BaseClientDetails();
        clientDetails.setClientId(clientId);
        clientDetails.setClientSecret(passwordEncoder.encode("123456"));
        clientDetails.setAuthorizedGrantTypes(Arrays.asList("refresh_token","authorization_code", "implicit","client_credentials", "password"));
        if(StringUtils.equals(clientId,"cli1")) {
            clientDetails.setScope(Arrays.asList("admin", "custom","server"));
        }
        else{
            clientDetails.setScope(Arrays.asList("guest"));
        }
        //设置token有效秒数
        clientDetails.setAccessTokenValiditySeconds(360);
        //设置refresh token有效秒数
        clientDetails.setRefreshTokenValiditySeconds(7200);
        HashSet<String> redirectUriSet = new HashSet<>();
        redirectUriSet.add("http://www.baidu.com");
        clientDetails.setRegisteredRedirectUri(redirectUriSet);
        return clientDetails;
    }

}
